<script setup>
import { listRecord } from "@/api/record";
import { ref, watch, computed } from "vue";
import MaterialTable from "@/components/MaterialTable.vue";
import PageSwitcher from "@/components/PageSwitcher.vue";
import LoadingLayer from "@/components/LoadingLayer.vue";

const PAGE_SIZE = 30;
const page = ref(1);
const pageLength = ref(1);
const data = ref([]);
const loading = ref(false);

async function fetchPage(page) {
  try {
    loading.value = true;
    const response = await listRecord((page - 1) * PAGE_SIZE, PAGE_SIZE);
    data.value = response.list;
    pageLength.value = Math.max(response.fullLength / PAGE_SIZE, 1);
  } catch (ex) {
    alert(ex);
  } finally {
    loading.value = false;
  }
}

fetchPage(1);

watch(page, async () => {
  await fetchPage(page.value);
});

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hour = date.getHours().toString().padStart(2, "0");
  const minute = date.getMinutes().toString().padStart(2, "0");
  const second = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

function extractType(row) {
  if (row.entry.extra["SYN"] != null) {
    return "SYN 扫描";
  }
}

const tableData = computed(() => {
  return data.value.map(row => {
    return {
      id: row.id,
      timestamp: formatDate(new Date(row.entry.main.timestamp)),
      type: extractType(row),
      from_ip: row.entry.extra["SYN"]?.from_ip,
      from_port: row.entry.extra["SYN"]?.from_port,
      to_port: row.entry.extra["SYN"]?.to_port
    };
  });
});

</script>

<template>
  <div class="details-table">
    <MaterialTable>
      <thead>
        <tr>
          <th>时间</th>
          <th>类型</th>
          <th>来源 IP</th>
          <th>来源端口</th>
          <th>目的端口</th>
        </tr>
      </thead>
      <tbody>
        <LoadingLayer fill :loading="loading"></LoadingLayer>
        <tr v-for="(row, index) in tableData" :key="index" :id="row.id">
          <td>{{ row.timestamp }}</td>
          <td>{{ row.type }}</td>
          <td>{{ row.from_ip }}</td>
          <td>{{ row.from_port }}</td>
          <td>{{ row.to_port }}</td>
        </tr>
      </tbody>
    </MaterialTable>
  </div>
  <PageSwitcher :value="page" :max="pageLength" @jump="value => page = value"></PageSwitcher>
</template>

<style scoped>
table {
  width: 100%;
}

#loading-layer {
  width: 100%;
  height: 100%;
}

.v-enter-active,
.v-leave-active {
  transition-property: opacity;
  transition-duration: var(--md-sys-motion-duration-short2);
  transition-timing-function: var(--md-sys-motion-easing-emphasized-decelerate);
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}

.details-table tbody {
  position: relative;
}
</style>
